import React, { PureComponent } from 'react';
import IceContainer from '@icedesign/container';
import { Input, Table, Dialog, Message, Button, NumberPicker, Grid } from '@alifd/next';
import styles from './index.module.scss';
import request from '../../../../utils/request';
import { host, stringCheck } from '../../../../const';
import axios from 'axios';
import classnames from 'classnames';
import './index.scss';
import MMap from '@/components/mMap';
import NImg from '@/components/nImg';
import WebStorageCache from 'web-storage-cache';

const wsCache = new WebStorageCache();

const { Row, Col } = Grid;

let ajaxTime = wsCache.get('ajaxTime') ? Number(wsCache.get('ajaxTime')) : 5000;
export default class Index extends PureComponent {
  static displayName = 'Index';

  static propTypes = {};

  static defaultProps = {};


  constructor(props) {
      super(props);
      this.state = {
          point: [],
          zoom: '',
          time: ajaxTime,
          newName: '',
          allSoliderList: [],
          battleId: '',
          battleDetail: {},
          log: '',
          lastTime: '',
          redVestStatisticsStr: '',
          blueVestStatisticsStr: '',
          orangeVestStatisticsStr: '',
          yellowVestStatisticsStr: '',
          redVestList: [],
          blueVestList: [],
          orangeVestList: [],
          battleEndDialogVisible: false,
      };
      this.isIndoorMap = false;
      this.timerID = null;
      this.logIdSet = new Set();
      this.isFirst = true;
  }

  componentDidMount() {
      this.refreshBattleDetail();
  }

  componentWillUnmount() {
      if (this.timerID != null) {
          clearInterval(this.timerID);
      }
  }


  refreshBattleDetail = () => {
      request({
          method: 'GET',
          url: `${host}/battle/now${this.state.lastTime == '' ? '' : `?last=${this.state.lastTime}`}`,
      }).then((res) => {
          const data = res?.data?.data;
          const mapEntity = data?.mapEntity;

          let point = [];
          let zoom = 10;
          const code = res?.data?.code;
          if (code === 200) {
              if (data == null) {
                  if (this.isFirst) {
                      Dialog.alert({
                          title: '战场实况',
                          content: '当前没有正在进行的演习',
                          okProps: { children: 'OK' },
                          onOk: () => location.href = '#/dashboard',
                      });
                  } else {
                      if (this.timerID != null) {
                          clearInterval(this.timerID);
                      }
                      this.setState({
                          battleEndDialogVisible: true,
                      });
                  }
              } else {
                  this.isFirst = false;
                  this.state.redVestList = [];
                  this.state.blueVestList = [];
                  this.state.orangeVestList = [];
                  this.state.yellowVestList = [];

                  let appendLog = '';

                  if (data.battleLogEntityList != null) {
                      const nowDate = new Date();
                      data.battleLogEntityList.forEach((log) => {
                          this.state.battleId = log.battleId;
                          if (this.logIdSet.has(log.id)) {
                              return true;
                          }
                          this.logIdSet.add(log.id);
                          appendLog = `${appendLog + log.time}      ${log.log}\n`;
                          // eslint-disable-next-line radix
                          if ((parseInt(new Date(log.time) - nowDate) / 1000) >= -10) {
                              if (log.log.type != 0) {
                                  const utterThis = new window.SpeechSynthesisUtterance(log.log);
                                  window.speechSynthesis.speak(utterThis);
                              }
                          }
                      });
                      this.state.log = this.state.log + appendLog;
                  }
                  const redVestStatistics = new Array(0, 0, 0, 0, 0);
                  const blueVestStatistics = new Array(0, 0, 0, 0, 0);
                  const orangeVestStatistics = new Array(0, 0, 0, 0, 0);
                  const yellowVestStatistics = new Array(0, 0, 0, 0, 0);
                  data.vestEntityList.forEach((vest) => {
                      let now;
                      vest.id = vest.num;
                      //   vest.name = `${Math.random()}`;
                      if (vest.team == 'red') {
                          now = redVestStatistics;
                          this.state.redVestList.push(vest);
                      } else if (vest.team == 'blue') {
                          now = blueVestStatistics;
                          this.state.blueVestList.push(vest);
                      } else if (vest.team == 'orange') {
                          now = orangeVestStatistics;
                          this.state.orangeVestList.push(vest);
                      } else if (vest.team == 'yellow') {
                          now = yellowVestStatistics;
                          this.state.yellowVestList.push(vest);
                      }
                      if (vest.status == 0) {
                          return true;
                      }
                      now[vest.hp / 25] = now[vest.hp / 25] + 1;
                  });
                  const tempRedVestStatisticsStr = `${'红方\n' + '正常：'}${redVestStatistics[4]}\n` + `轻伤：${redVestStatistics[3]}\n` + `中伤：${redVestStatistics[2]}\n` + `重伤：${redVestStatistics[1]}\n` + `阵亡：${redVestStatistics[0]}\n`;
                  const tempBlueVestStatisticsStr = `${'蓝方\n' + '正常：'}${blueVestStatistics[4]}\n` + `轻伤：${blueVestStatistics[3]}\n` + `中伤：${blueVestStatistics[2]}\n` + `重伤：${blueVestStatistics[1]}\n` + `阵亡：${blueVestStatistics[0]}\n`;
                  const tempOrangeVestStatisticsStr = `${'人质\n' + '正常：'}${orangeVestStatistics[4]}\n` + `轻伤：${orangeVestStatistics[3]}\n` + `中伤：${orangeVestStatistics[2]}\n` + `重伤：${orangeVestStatistics[1]}\n` + `阵亡：${orangeVestStatistics[0]}\n`;
                  const tempYellowVestStatisticsStr = `${'劫匪\n' + '正常：'}${yellowVestStatistics[4]}\n` + `轻伤：${yellowVestStatistics[3]}\n` + `中伤：${yellowVestStatistics[2]}\n` + `重伤：${yellowVestStatistics[1]}\n` + `阵亡：${yellowVestStatistics[0]}\n`;
                  if (mapEntity) {
                      point = [mapEntity.lng, mapEntity.lat];
                      zoom = mapEntity.zoom;
                      this.isIndoorMap = !!mapEntity?.type;
                  }
                  this.setState({
                      point,
                      zoom,
                      redVestStatisticsStr: tempRedVestStatisticsStr,
                      blueVestStatisticsStr: tempBlueVestStatisticsStr,
                      orangeVestStatisticsStr: tempOrangeVestStatisticsStr,
                      yellowVestStatisticsStr: tempYellowVestStatisticsStr,
                      battleDetail: data,
                      allSoliderList: data.vestEntityList,
                  });
                  console.log('测试 ~ file: index.jsx ~ line 173 ~ Index ~ data.vestEntityList', data.vestEntityList);

                  if (this.refs.myref) {
                      this.refs.myref.drarPoint(data.vestEntityList);
                  }
                  this.state.lastTime = new Date().Format('yyyy-MM-dd HH:mm:ss');
                  console.log(ajaxTime, 'ajaxTime');
                  if (this.timerID == null) {
                      this.timerID = setInterval(() => {
                          this.refreshBattleDetail();
                      }, ajaxTime);
                  }
              }
          }
      });
  }

  renderPosCell = (value, index, record) => `${record.lat} ${record.lng}`

  renderStatus = (value, index, record) => {
      if (record.status == 0) {
          return <a style={{ color: 'red' }}>离线</a>;
      }
      if (record.hp > 0) {
          return <a style={{ color: 'green' }}>正常</a>;
      }
      if (record.hp == 0) {
          return <a style={{ color: 'red' }}>阵亡</a>;
      }
  }

  renderOper = (value, index, record) => {
      if (record.status == 0) {
          return ' ';
      } else if (record.hp > 0) {
          const oper1 = <a href="javascript:;" onClick={this.sendDieSingle.bind(this, record)}>判死</a>;
          const oper2 = <a href="javascript:;" onClick={this.showReloadDialog.bind(this, record)}>主武器充弹</a>;
          const oper3 = <a href="javascript:;" onClick={this.sendInjureSingle.bind(this, record)}>判伤</a>;
          const oper4 = <a href="javascript:;" onClick={this.showReloadDialog2.bind(this, record)}>副武器充弹</a>;
          // const oper5 = <a href="javascript:;" onClick={this.changeName.bind(this, record)}>修改名字</a>;
          return (
              <div>
                  {oper1} &nbsp;{oper2}<br /> {oper3}&nbsp; {oper4}&nbsp;
              </div>
          );
      } else if (record.hp == 0) {
          return (
              <div><a href="javascript:;" onClick={this.sendLiveSingle.bind(this, record)}>判活</a> </div>
          );
      }
  }

  showReloadDialog = (record) => {
      Dialog.alert({
          title: '主武器装弹',
          onOk: this.submitVestReload.bind(this, record),
          content:
  <p>
      <p>{record.num}号</p>
      <p> <NumberPicker id="vestAmmoInput" type="inline" step={1} min={1} max={999} defaultValue={30} /></p>
  </p>,
      });
  }

  submitVestReload = (record) => {
      request({
          method: 'GET',
          url: `${host}/vest/reload?vestNum=${record.num}&ammo=${document.getElementById('vestAmmoInput').value}&weapon=2`,
      }).then(() => {
          Message.success(`${record.num}号主武器装弹成功`);
      });
  }

  changeName = (record) => {
      Dialog.alert({
          title: '修改名字',
          onOk: this.setVestName.bind(this, record),
          content:
  <p>


      <p> <Input onChange={(value) => {
          this.setState({
              newName: value,
          });
      }}
      />
      </p>
  </p>,
      });
  }
  showReloadDialog2 = (record) => {
      Dialog.alert({
          title: '副武器装弹',
          onOk: this.submitVestReload2.bind(this, record),
          content:
  <p>
      <p>{record.num}号</p>
      <p> <NumberPicker id="vestAmmoInput2" type="inline" step={1} min={1} max={999} defaultValue={30} /></p>
  </p>,
      });
  }

  submitVestReload2 = (record) => {
      request({
          method: 'GET',
          url: `${host}/vest/reload?vestNum=${record.num}&ammo=${document.getElementById('vestAmmoInput2').value}&weapon=3`,
      }).then(() => {
          Message.success(`${record.num}号副武器装弹成功`);
      });
  }

  sendInjureSingle = (record) => {
      request({
          method: 'GET',
          url: `${host}/vest/injure/${record.num}`,
      }).then(() => {
          Message.success(`${record.num}号受伤判定信号发送成功`);
      });
  }


  sendDieSingle = (record) => {
      request({
          method: 'GET',
          url: `${host}/vest/die/${record.num}`,
      }).then(() => {
          Message.success(`${record.num}号死亡判定信号发送成功`);
      });
  }

  sendLiveSingle = (record) => {
      request({
          method: 'GET',
          url: `${host}/vest/live/${record.num}`,
      }).then(() => {
          Message.success(`${record.num}号复活判定信号发送成功`);
      });
  }

  endBattle = () => {
      Message.success('演习结束');
      request({
          method: 'GET',
          url: `${host}/battle/end`,
      }).then(() => {
          wsCache.set('mapType', '');
          console.log('ws清除了mapType');
      });
  }

  reloadAll = () => {
      const ammo = document.getElementById('ammoInput').value;
      if (stringCheck(ammo) == null) {
          Message.error('请输入初始弹量');
      } else {
          request({
              method: 'GET',
              url: `${host}/vest/reloadAll?ammo=${ammo}&weapon=2`,
          }).then(() => {
              Message.success('全体主武器指令下发成功');
              this.state.battleDetail.isLoadAmmo = 1;
              this.forceUpdate();
          });
      }
  }

  reloadAll2 = () => {
      const ammo = document.getElementById('ammoInput2').value;
      if (stringCheck(ammo) == null) {
          Message.error('请输入初始弹量');
      } else {
          request({
              method: 'GET',
              url: `${host}/vest/reloadAll?ammo=${ammo}&weapon=3`,
          }).then(() => {
              Message.success('全体副武器指令下发成功');
              this.state.battleDetail.isLoadAmmo2 = 1;
              this.forceUpdate();
          });
      }
  }

  renderEditCell = (value, index, record) => <Input autoFocus defaultValue={value} onBlur={this.setVestName.bind(this, record)} />

  setVestName = (record) => {
      const newName = this.state.newName;
      if (stringCheck(newName) != null) {
          request({
              method: 'GET',
              url: `${host}/vest/name/${record.num}/${newName}`,
          }).then(() => {
              Message.success('姓名修改成功');
              this.setState({
                  newName: '',
              });
          });
      }
  }

  fakeClick = (obj) => {
      const ev = document.createEvent('MouseEvents');
      ev.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
      obj.dispatchEvent(ev);
  }

  exportTxt = () => {
      const urlObject = window.URL || window.webkitURL || window;
      const exportBlob = new Blob([this.state.log]);
      const saveLink = document.createElementNS('http://www.w3.org/1999/xhtml', 'a');
      saveLink.href = urlObject.createObjectURL(exportBlob);
      saveLink.download = `${new Date().Format('yyyy-MM-dd')}演习实况.txt`;
      this.fakeClick(saveLink);
  }

  exportExcel = () => {
      const data = {};
      data.red = this.state.redVestList;
      data.blue = this.state.blueVestList;
      data.orange = this.state.orangeVestList;
      data.yellow = this.state.yellowVestList;

      axios.post(`${host}/battle/export/excel/${this.state.battleId}`, data, { responseType: 'blob' })
          .then((response) => {
              const blob = new Blob([response.data]);
              const downloadElement = document.createElement('a');
              const href = window.URL.createObjectURL(blob); // 创建下载的链接
              downloadElement.href = href;
              downloadElement.download = `${new Date().Format('yyyy-MM-dd')}演习实况.xlsx`;
              document.body.appendChild(downloadElement);
              downloadElement.click(); // 点击下载
              document.body.removeChild(downloadElement); // 下载完成移除元素
              window.URL.revokeObjectURL(href); // 释放掉blob对象

              console.log(response);
          })
          .catch((error) => {
              console.log(error);
          });
  }

  changeTime = () => {
      ajaxTime = this.state.time;
      wsCache.set('ajaxTime', ajaxTime);
  }

  render() {
      return (

          <IceContainer className={classnames('lite-table', styles.wrap)}>

              <Row >
                  <Col span={24}>  <div style={{ width: '100%', height: '50vh', maxWidth: 'calc(100vw - 60px - 200px)' }} className={styles.itemWrap} >
                      {/* <img src={this.state.mapBase64} /> */}

                      {
                          this.isIndoorMap ? <NImg mapBase64={this.state.battleDetail.mapBase64} showFullButton /> :
                              this.state.point && this.state.point.length ?
                                  <MMap ref="myref" showFullButton defaultCenter={this.state.point} defaultZoom={this.state.zoom} list={this.state.allSoliderList} />

                                  : null
                      }


                  </div>
                  </Col>
              </Row>
              <Row >
                  <Col span={24}>     <div style={{ width: '100%', height: '100%' }} className={styles.itemWrap} >


                      <div style={{
                          width: '100%', height: '100%', display: 'flex', flexDirection: 'column',
                      }}
                      >

                          <div className="title" style={{ display: 'flex', justifyContent: 'center', flex: '1' }}>

                              <Input.TextArea style={{ width: '50%', height: '100%' }} rows={6} value={this.state.log} /> &nbsp;
                              <Input.TextArea style={{ width: '10%', height: '100%' }} rows={6} value={this.state.redVestStatisticsStr} /> &nbsp;
                              <Input.TextArea style={{ width: '10%', height: '100%' }} rows={6} value={this.state.blueVestStatisticsStr} />&nbsp;
                              <Input.TextArea style={{ width: '10%', height: '100%' }} rows={6} value={this.state.orangeVestStatisticsStr} /> &nbsp;
                              <Input.TextArea style={{ width: '10%', height: '100%' }} rows={6} value={this.state.yellowVestStatisticsStr} />

                          </div>
                          <div className="title" style={{ display: 'flex', marginTop: '10px', justifyContent: 'center' }}>
                              <NumberPicker id="ammoInput" style={{ width: '100px' }} min={1} max={999} placeholder="初始弹量" />&nbsp;
                              <Button type="primary" onClick={this.reloadAll} disabled={this.state.battleDetail == null ? true : this.state.battleDetail.isLoadAmmo != 0}>全体主武器充弹</Button>&nbsp;
                  &nbsp;&nbsp;&nbsp;&nbsp;
                              <NumberPicker id="ammoInput2" style={{ width: '100px' }} min={1} max={999} placeholder="初始弹量" />&nbsp;
                              <Button type="primary" onClick={this.reloadAll2} disabled={this.state.battleDetail == null ? true : this.state.battleDetail.isLoadAmmo2 != 0}>全体副武器充弹</Button>&nbsp;
                              <Button type="primary" warning onClick={this.endBattle}>演习结束</Button>&nbsp;&nbsp;
                              <NumberPicker
                                  value={this.state.time}
                                  onChange={(value) => {
                                      this.setState({
                                          time: value,
                                      });
                                  }}
                                  style={{ width: '150px' }}
                                  min={1}
                                  max={100000}
                                  placeholder="轮询时间(毫秒)"
                              />&nbsp;
                              <Button type="primary" onClick={this.changeTime}>修改轮询时间</Button>
                          </div>

                      </div>


                  </div>

                  </Col>
              </Row>
              <Row >
                  <Col span={24} >
                      <div style={{ width: '100%' }} className={styles.itemWrap} >
                          <h1 style={{ color: 'red' }}>红方</h1>
                          <Table dataSource={this.state.redVestList} hasBorder={false}>
                              <Table.Column title="编号" dataIndex="num" />
                              {/* <Table.Column title="人员" width={125} dataIndex="name" cell={this.renderEditCell} /> */}
                              <Table.Column title="主武器" dataIndex="weapon1" />
                              <Table.Column title="弹药量1" dataIndex="ammo1" />
                              <Table.Column title="生命值" dataIndex="hp" />
                              <Table.Column title="副武器" dataIndex="weapon2" />
                              <Table.Column title="弹药量2" dataIndex="ammo2" />
                              <Table.Column title="状态" cell={this.renderStatus} />
                              <Table.Column title="操作" width={200} cell={this.renderOper} />
                          </Table>
                      </div>
                      <div style={{ width: '100%' }} className={styles.itemWrap} >
                          <h1 style={{ color: 'blue' }}>蓝方</h1>
                          <Table dataSource={this.state.blueVestList} hasBorder={false}>
                              <Table.Column title="编号" dataIndex="num" />
                              {/* <Table.Column title="人员" width={125} dataIndex="name" cell={this.renderEditCell} /> */}
                              <Table.Column title="主武器" dataIndex="weapon1" />
                              <Table.Column title="弹药量1" dataIndex="ammo1" />
                              <Table.Column title="生命值" dataIndex="hp" />
                              <Table.Column title="副武器" dataIndex="weapon2" />
                              <Table.Column title="弹药量2" dataIndex="ammo2" />
                              <Table.Column title="状态" cell={this.renderStatus} />
                              <Table.Column title="操作" width={200} cell={this.renderOper} />
                          </Table>
                      </div>
                      <div style={{ width: '100%' }} className={styles.itemWrap} >
                          <h1 style={{ color: 'orange' }}>人质</h1>
                          <Table dataSource={this.state.orangeVestList} hasBorder={false}>
                              <Table.Column title="编号" dataIndex="num" />
                              {/* <Table.Column title="人员" width={125} dataIndex="name" cell={this.renderEditCell} /> */}
                              <Table.Column title="主武器" dataIndex="weapon1" />
                              <Table.Column title="弹药量1" dataIndex="ammo1" />
                              <Table.Column title="生命值" dataIndex="hp" />
                              <Table.Column title="副武器" dataIndex="weapon2" />
                              <Table.Column title="弹药量2" dataIndex="ammo2" />
                              <Table.Column title="状态" cell={this.renderStatus} />
                              <Table.Column title="操作" width={200} cell={this.renderOper} />
                          </Table>
                      </div>
                      <div style={{ width: '100%' }} className={styles.itemWrap} >
                          <h1 style={{ color: 'brown' }}>劫匪</h1>
                          <Table dataSource={this.state.yellowVestList} hasBorder={false}>
                              <Table.Column title="编号" dataIndex="num" />
                              {/* <Table.Column title="人员" width={125} dataIndex="name" cell={this.renderEditCell} /> */}
                              <Table.Column title="主武器" dataIndex="weapon1" />
                              <Table.Column title="弹药量1" dataIndex="ammo1" />
                              <Table.Column title="生命值" dataIndex="hp" />
                              <Table.Column title="副武器" dataIndex="weapon2" />
                              <Table.Column title="弹药量2" dataIndex="ammo2" />
                              <Table.Column title="状态" cell={this.renderStatus} />
                              <Table.Column title="操作" width={200} cell={this.renderOper} />
                          </Table>
                      </div>

                  </Col>
              </Row>

              <Dialog
                  title="战场实况"
                  visible={this.state.battleEndDialogVisible}
                  onOk={this.exportExcel}
                  onClose={() => { location.href = '#/dashboard'; }}
                  onCancel={() => { location.href = '#/dashboard'; }}
                  okProps={{ children: '导出Excel' }}

                  cancelProps={{ children: '退出' }}
              >
                  <div className="msg" dangerouslySetInnerHTML={{ __html: this.state.log.replace(new RegExp('\n', 'gm'), '<br />') }} />

              </Dialog>
          </IceContainer>

      );
  }
}
